﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;

namespace net.entity.framework.common {
    public static class EnumerableExtender {
        public static bool IsEmpty<T>(this IEnumerable<T> items) {
            try {
                return ReferenceEquals(items.First(), null);
            } catch {
                return true;
            }
        }


        public static T LookupOrDefault<T>(this IEnumerable<T> items, Expression<Func<T, bool>> whereClause,
                                           T defaultValue) {
            var searchResults = items.Where(whereClause.Compile());
            return searchResults.IsEmpty() ? defaultValue : searchResults.First();
        }

        public static T Lookup<T>(this IEnumerable<T> items, Expression<Func<T, bool>> whereClause, bool strict) {
            var searchResults = items.Where(whereClause.Compile());
            if (!searchResults.IsEmpty()) {
                return searchResults.First();
            }
            if (strict) {
                throw new Exception("Value not found");
            }

            return default(T);
        }
    }
}